// 公共头部 uni-transition
import myHeader from "/pages/headerfoot/pages/header.vue";
//过度动画
import uTransition from "/uni_modules/uni-transition/components/uni-transition/uni-transition.vue"
//语言
import Lang from '/utils/lang.js';
//cache缓存
import Cache from '@/utils/cache.js';
//打帮赛方法
import hitmatchcommon from '@/common/hitmatchcommon.js';
// 基础方法
import Base from "/common/base.js";

export default {
	props: {
		code: String,
		project_make_id: String,
		project_id: String,
		gametype: String,
		initiator: String
	},
	components: {
		myHeader,
		uTransition,
	},
	data() {
		return {
			upishow: true, //是否问题显示、
			downishow: false, //是否答案显示、
			modeClass: 'fade',
			timer: ['fade', 'slide-left'], //定时器
			questions: '', //出题
			countdownstr: Lang.lang.countdown, //倒计时
			answer: [], //答案

			itemAdd: 2, //每隔itemAdd道题itemLen++

			sucesswtopic: 0, //正确题数
			errorwtopic: 0, //错误题数
			second: 100, //间隔毫秒数
			show: true, //显示开始
			times: '0', //分钟
			seconds: '00', //秒
			level: 1, //等级
			
			addLevel:0, //每4题增加难度，前5级
			one_score: 0, //每正确一题10分
			items: 0, //生成5个错误选项，外加一个正确选项，共六个选项
			
			theCurrentRule: [], //当前规则
			tikuArr: [], //组装数组
			ifcountdown: false, //是否显示倒计时
			flaseMax: 10, //最大错题数量
			theCurrentNumberOfQuestions: 0, //当前题数
			ifpass: false, //闯关显示
			btna: ['返回项目选择', '查看排行榜', '再次打榜','提交分数'],
			totalscore: 0, //总分数
			tiku_data: {
				tx: ["●", "★", "◆", "■", "▲", "☆", "○", "◇", "□", "△"],
				zm: ["q", "w", "e", "r", "t", "y", "u", "i", "p", "a", "s", "d", "f", "g", "h", "j", "k", "z",
					"x", "c", "v", "b", "n", "m"
				],
				wz: ['坝', '汉', '艳', '扮', '杨', '读', '摔', '跤', '凤', '洁', '晨', '绒', '球', '服', '装', '静', '停'],
				sz: ["2", "3", "4", "5", "6", "7", "8", "9"],
				fh: ["#", "$", "%", "!", "*", "~", "￥"],
			}, //题库数据
			selectedindex: 99, //选中特效数字 99没有数字
			clickStyles: '', //点击样式
			iffirststart:1,//第一次进入
			 successnumberarr:[],//问题
			 my_answer:[],//我的答案
			 answertime:0,//答题用时
			level_data: {},//难度
			coding:0,//编码
			project_user_achievement_end:0, //提交分数 0=未提交 1=提交
		}
	},
	async mounted() {
		var that = this;
		console.log(that.gametype);//对战类型
		console.log(that.initiator);//发起人
		
		//console.log(that.code);//编码
		if(that.code){
			that.coding=that.code;
		}else{
			 that.coding=new Date().getTime();//设置编码
		}
		//console.log(that.project_make_id);//赛事
		if(that.project_make_id){
			Cache.set('project_make_id',that.project_make_id)
		}
		//console.log(that.project_id);//项目
		if(that.project_id){
			Cache.set('project_id',that.project_id)
		}
		
		
		 var data=await that.getMakeProjecParameter();//得到项目配置
		 that.level_data=data.make_project_parameter_list;
		 that.getTheCorrectQuestion(); //获取正确题	
	},
	methods: {


		//开始游戏
		begin() {
			var that = this;
			that.show = false; //显示开始
			//开始答题
			that.handle();
		},
		//开始答题
		handle() {
			var that = this;
			//生成错误题
			that.generateErrorQuestions();
			// 正确题与错误题打乱
			that.dislocate();
			//定时器；
			var timersa = setTimeout(() => {
				that.ifcountdown = true; //是否显示倒计时
				that.countdown(); //倒计时
				clearTimeout(timersa);
				that.upishow = !that.upishow; //是否问题显示、
				that.downishow = !that.downishow; //是否答案显示
			}, parseInt(that.theCurrentRule['flash_time']) * that.second);
		},
		//得到项目配置
		 getMakeProjecParameter() {
			var that = this;
			var data = {};
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			
			return new Promise((resolve, reject) => {
				   hitmatchcommon.getMakeProjecParameterLibMethod(data).then(res => {
					if (res) {
						resolve(res)
					}
				});
			})
		},
		//点击特效
		clickEffects(number) {
			var that = this;
			that.selectedindex = number
		},
		//点击事件
		clickhandle(e, number) {
			var that = this;
			that.iffirststart=2;//不是第一个
			if (e == that.questions) { //正确
				that.sucesswtopic++;
				that.clickStyles = 'selected_sucess';
			} else { //错误
				that.errorwtopic++;
				that.clickStyles = 'selected_error';
			}
			
			that.successnumberarr.push(that.questions),//问题
			that.my_answer.push(e);//我的答案
			
			//点击特效
			that.clickEffects(number);

			setTimeout(function() {
				//重置数据
				that.resetTheData();
				//显示中间过渡
				that.intermediateTransition();
				that.selectedindex = 99; //选中特效数字 99没有数字
				setTimeout(function() {
					that.begin();
				}, that.theCurrentRule['flash_time'] * 1000); // 这里的 1000 表示延时的时间，单位是毫秒
			}, 1000); // 这里的 1000 表示延时的时间，单位是毫秒

		},
		//重置数据
		resetTheData() {
			var that = this;
			that.answer = []; //重置题目
			that.questions = []; //重置答案	
		},
		//显示中间过渡
		intermediateTransition() {
			var that = this;
			//时间结束
			clearInterval(that.timer)

			that.getTheCorrectQuestion(); //获取正确题

			that.upishow = true; //是问题显示、
			that.downishow = false; //是答案显示

			that.show = true; //显示开始
			that.ifcountdown = false; //是否显示倒计时
		},
		//确认提交
		confirmsubmit() {
			var that = this;
			uni.showModal({
				title: '提示',
				content: '确定提交吗？',
				success: function(res) {
					if (res.confirm) {
						//提交
						that.submit();
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});

		},
		//提交
		submit() {
			var that = this;
			//时间结束
			clearInterval(that.timer)
			
			//计算分数
			that.calculateTheScore();
			that.ifpass = true;
		
			var that = this;
			var data = {};
			data['project_id'] = Cache.get('project_id');
			data['make_user_id'] = Cache.get('user_id');
			data['make_id'] = Cache.get('project_make_id');
			data['questions_answer'] =that.successnumberarr;//问题
			data['my_answer'] = that.my_answer;//我的答案
			data['answertime'] =that.answertime;//答题用时
			data['allscore'] = that.totalscore;//我的分数
			data['level'] =that.level;//关卡
			data['clearance'] = 1;//是否过关
			data['topic'] = that.nowfrequency;//题数
			data['make_project_user_code'] = that.coding; //编码
			data['project_user_achievement_end'] = that.project_user_achievement_end; //提交分数 0=未提交 1=提交
			
			hitmatchcommon.setProjectUserAchievementLibMethod(data);//提交分数
			return;
		},
		//点击判断
		clickList(e) {
			var that = this;
			//返回项目选择
			if (e == '0') {
				uni.reLaunch({
						url:hitmatchcommon.automaticurl('matcheslist')+"?id="+ Cache.get('project_make_id'),
				})
			}
			//排行榜
			if (e == '1') {
				 uni.reLaunch({
				 	url:hitmatchcommon.automaticurl('ranking')+"?id="+ Cache.get('project_make_id'),
				 })
			}
			//再次打榜
			if (e == 2) {
				that.errorwtopic = 0; //正确题
				that.sucesswtopic = 0; //错误题
				that.ifpass = false; //关闭闯关界面
				that.level = 1; //等级
				that.theCurrentNumberOfQuestions = 0; //当前题数
				that.getTheCorrectQuestion(); //获取正确题
			}
			//提交分数
			if (e == '3') {
				//提交分数 0=未提交 1=提交
				that.project_user_achievement_end=1;
				that.submit();
				Base.publicshowtoastsuccess('提交成功',hitmatchcommon.automaticurl('matcheslist') + "?id=" + Cache.get('project_make_id'));
			}
		},
		//错误达到限制
		overTopic() {
			var that = this;
			if (that.errorwtopic >= that.flaseMax) {
				//提交
				that.submit();
				console.log("错误达到限制");
				// return;
			}
		},
		//计算分数
		calculateTheScore() {
			var that = this;
			that.totalscore = that.one_score * that.sucesswtopic; //总分数
		},
		//等级提升
		levelUp() {
			var that = this;
			console.log(that.level);
			if (that.level <= 5) {
				if (that.theCurrentNumberOfQuestions > that.addLevel) {
					that.theCurrentNumberOfQuestions = 0; //重置当前题
					that.level++; //提升等级
				}
			} else {
				if (that.level < 8) { //6-8级
					if (that.theCurrentNumberOfQuestions >= that.level_data[that.level + 1]['num'] - 1) {
						that.theCurrentNumberOfQuestions = 0; //重置当前题
						that.level++; //提升等级
					}
				}
				if (that.theCurrentNumberOfQuestions % that.itemAdd == 0) { //每itemAdd题增加一个字符
					that.theCurrentRule['num']++;
				}
			}
		},
		//倒计时
		countdown() {
			var that = this;
			var times = parseInt(that.times); //分钟
			var seconds = parseInt(that.seconds); //秒
			that.timer = setInterval(() => {
				that.answertime++; //答题用时
				if (seconds <= 0) {
					if (times > 0) {
						that.seconds = seconds = 59;
						that.times = --times; //减分钟
					} else {
						//错误
						that.errorwtopic++;
						//重置数据
						that.resetTheData();
						//显示中间过渡
						that.intermediateTransition();
						//时间结束
						clearInterval(that.timer)
					}
				} else {
					--seconds; //减秒数
					if (seconds <= 9) {
						that.seconds = '0' + seconds;
					} else {
						that.seconds = seconds;
					}
				}
			}, 1000);
		},
		//获取正确题 
		getTheCorrectQuestion() {
			var that = this;
			that.one_score = that.level_data[that.level]['one_score']; //获取当前分数
			that.addLevel = that.level_data[that.level]['addLevel'];//每4题增加难度，前5级
			that.items = that.level_data[that.level]['items']; //生成5个错误选项，外加一个正确选项，共六个选项
			
			//当前题数
			that.theCurrentNumberOfQuestions++;
			//错误达到限制
			that.overTopic();
			//等级提升
			that.levelUp();

			that.theCurrentRule = that.level_data[that.level]; //获取当前规则
		
 
			// console.log(that.theCurrentRule);
			//倒计时秒数
			that.seconds = '0' + that.theCurrentRule['one_time'];
			//题目组合 
			that.combinationOfTopics();
			//随机题正确题
			that.correctQuestion();
		},

		// 正确题与错误题打乱
		dislocate() {
			var that = this;
			var success = that.questions; //正确题
			var error = that.answer; //错误题
			var arr = error.concat([success]); //合并
			//打乱
			that.answer = that.shuffle(arr);
		},
		//生成错误题
		generateErrorQuestions() {
			var that = this;
			for (var i = 0; i < that.items; i++) {
				//替换字符可变项
				that.substitutionCharacters();
			}
		},
		//替换字符可变项
		substitutionCharacters() {
			var that = this;

			var newtikuArr = JSON.parse(JSON.stringify(that.tikuArr)); //重新赋值组装数组
			var questions = JSON.parse(JSON.stringify(that.questions)); //重新赋值正常答案
			var randIndex1 = Math.round(Math.random() * (questions.length - 1)); //随机取一个数
			questions.splice(randIndex1, 1); //重新赋值正常答案

			var nowtopic = questions[randIndex1]; //查询重新赋值组装数组指定值的位置


			var oldStrIndex = newtikuArr.indexOf(nowtopic); //删除指定重新赋值组装数组的index

			newtikuArr.splice(oldStrIndex, 1); //删除已随机选中的字符串下标

			var randIndex2 = Math.round(Math.random() * (newtikuArr.length - 1)); //随机取一个数
			var nowtopicb = newtikuArr[randIndex2]; //组装数组提取一个
			// var newarr = questions.concat(nowtopicb); //组装数组
			var newquestionsc = [];
			var newquestionsa = questions.slice(0, randIndex1 + 1);
			var newquestionsb = questions.slice(randIndex1 + 1, questions.length)

			newquestionsc = newquestionsa;
			newquestionsc.push(nowtopicb);
			var len = newquestionsb.length;
			for (var i = 0; i < len; i++) {
				newquestionsc.push(newquestionsb[i]);
			}

			that.answer.push(newquestionsc); //推入错误题库
		},
		//随机题
		correctQuestion() {
			var that = this;
			// console.log(tikuArrs);
			var newtikuArr = that.tikuArr; //重新赋值
			var arr = [];
			for (var i = 0; i < that.theCurrentRule['num']; i++) {
				var randIndex1 = Math.round(Math.random() * (newtikuArr.length - 1)); //随机取一个数
				arr.push(that.tikuArr[randIndex1]);
			}
			that.questions = arr; //存入题	
			// console.log(arr);
		},
		//题目组合
		combinationOfTopics() {
			var that = this;
			var type = that.theCurrentRule['type']; //获取类型
			var arr = []; //组合数组
			type.forEach((v, i) => {
				var one_tiku = that.tiku_data[v]; //获取题目
				arr = arr.concat(one_tiku)
			})
			that.tikuArr = that.shuffle(arr); // 存入数组
		},
		//打乱数组
		shuffle(arr) {
			var len = arr.length;
			for (var i = 0; i < len; i++) {
				var end = len - 1;
				var index = (Math.random() * (end + 1)) >> 0;
				var t = arr[end];
				arr[end] = arr[index];
				arr[index] = t;
			}
			return arr;
		},
	}
}